/*
 * @Author: sjf 1758142861@qq.com
 * @Date: 2023-03-16 18:20:15
 * @LastEditors: sjf 1758142861@qq.com
 * @LastEditTime: 2023-03-17 17:14:44
 * @FilePath: /D_C_lib/lw_process/day2/mythread1.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<vector>
#include<cassert>
#include<unistd.h>
#include<pthread.h>

using namespace std;

class __thread_data
{
public:
    pthread_t tid;
    char namebuffer[64];
};

//1.该函数一共被NUM个线程调用，我们知道当一个函数被多个执行流访问，该函数的状态叫做重入状态.
//2.该函数是一个可重入函数
//3.在函数内部定义的变量都叫做临时变量，具有临时性
void* start_routine(void* args)
{
    __thread_data *td = static_cast<__thread_data*>(args);
    int count = 10;
    while(count)
    {
        std::cout << "new thread create succes,name:" << td->namebuffer << "count:" << count-- << std::endl;
        sleep(1); 
    }
    //const char* name = static_cast<const char*>(args);
    //std::cout << "i am new pthread name:" << name << std::endl;
    delete td;
    pthread_exit(nullptr);
    //return nullptr;
}

int main()
{
    vector<pthread_t> tids;
    vector<__thread_data*> threads;
#define NUM 10
    for(int i = 0; i < NUM; i++)
    {
        __thread_data *td = new __thread_data();
        snprintf(td->namebuffer,sizeof(td->namebuffer),"%s:%d","thread",td->namebuffer,i+1);
        pthread_create(&td->tid,nullptr,start_routine,td);
        threads.push_back(td);
        //pthread_t tid;
        //char buffer[64];
        //snprintf(buffer,sizeof(buffer),"%s:%d","thread",buffer,i);
        //pthread_create(&tid,nullptr,start_routine,(void*)"thread one");
        //pthread_create(&tid,nullptr,start_routine,buffer);
    }

    for(auto& iter : threads)
    {
        std::cout << "create thread:" << iter->namebuffer << " : " << iter->tid << "success" << std::endl;
    }
    while(true)
    {
        std::cout << "new thread create succes,name: main thread" << std::endl;
        sleep(1);
    }
    return 0;
}